import datetime
import jwt
import json
from django.conf import settings
from django.http import JsonResponse
from django.views import View
from numpy import delete

from scuiproject.models import Depart, Menu, Metalist, Role, User

# 登录


class Login(View):
    def post(self, request):
        params = json.loads(request.body)
        userModel = User.objects.get(user=params.get(
            'user'), password=params.get('password'))
        result = {}
        if userModel is not None:
            headers = {
                'typ': 'jwt',
                'alg': 'HS256'
            }
            # 构造payload
            payload = {
                'user': userModel.user,  # 自定义用户名
                'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=5)  # 超时时间
            }
            data = {}
            token = jwt.encode(payload=payload, key=settings.SECRET_KEY,
                               algorithm="HS256", headers=headers)
            result['massage'] = '登陆成功啦'
            result['code'] = 200
            result['data'] = {}
            result['data']['token'] = token
            result['data']['userInfo'] = userModel.user

        else:
            result['massage'] = '登陆失败'
            result['status'] = 'error'
        return JsonResponse(result)

# 用户信息的获取和创建,多对多正向查询、创建


class UsersModel(View):
    def get(self, request):
        try:
            userinfo = User.objects.all()
            # print(',,,,,,,,,,,,,',userinfo.values())
            userlist = []
            for i in userinfo:
                print(i.depart)
                userlist.append(
                    {
                        'id': i.id,
                        'user': i.user,
                        'phone': i.phone,
                        'password': i.password,
                        'create_time': i.create_time,
                        'role': list(i.role.all().values()),
                        'headPicture': i.headPicture,
                        'nickName': i.nickName,
                        'status':i.status,
                        'depart': {
                            'id': i.depart.id,
                            'depName': i.depart.depName,
                            'statu': i.depart.statu,
                            'depTime': i.depart.depTime,
                            'children': list(i.depart.children.values())
                        }
                    }
                )
            return JsonResponse({
                'code': 200,
                'message': '获取用户信息成功',
                'data': userlist
            }, safe=False)
        except:
            return JsonResponse({
                'code': 400,
                'message': '获取用户信息失败'
            })

    def post(self, request):
        data = json.loads(request.body)
        did = data['depart']
        depinfo = Depart.objects.get(id=did)
        user = User.objects.create(user=data['user'], password=data['password'],
                                   phone=data['phone'], create_time=data['create_time'],
                                   status=data['status'],
                                   headPicture=data['headPicture'], nickName=data['nickName'], depart=depinfo)
        user.role.set(data['role'])

        return JsonResponse({'code': 200, 'message': '添加数据成功'})


class UserModel(View):
    def get(self, request, pk):
        try:
            userinfo = User.objects.get(id=pk)
        except:
            return JsonResponse({'error': '错误信息'}, status=400)
        return JsonResponse(
            {'code': 200, 'message': '请求成功', 'data': {
                'id': userinfo.id,
                'user': userinfo.user,
                'password': userinfo.password,
                'phone': userinfo.phone,
                'create_time': userinfo.create_time,
                'headPicture': userinfo.headPicture,
                'role': list(userinfo.role.all().values()),
                'nickName': userinfo.nickName,
                'status':userinfo.status,
                'depart': {
                    'id': userinfo.depart.id,
                    'depName': userinfo.depart.depName,
                    'statu': userinfo.depart.statu,
                    'depTime': userinfo.depart.depTime,
                    'children': list(userinfo.depart.children.values())
                }

            }}
        )

    def put(self, request, pk):
        data = json.loads(request.body)
        print(',,,,,,,,,,,,,,,,,,,',data)
        user = data.get('user')
        password = data.get('password')
        phone = data.get('phone')
        create_time = data.get('create_time')
        headPicture = data.get('headPicture')
        nickName = data.get('nickName')
        depart = data.get('depart')
        status=data.get('status')

        userinfo = User.objects.get(id=pk)
        userinfo.user = user
        userinfo.password = password
        userinfo.phone = phone
        userinfo.create_time = create_time
        userinfo.headPicture = headPicture
        userinfo.nickName = nickName
        userinfo.status = status
        # userinfo.role.set(data['role'])
        # userinfo.depart = depart['id']

        userinfo.save()

        return JsonResponse(
            {'code': 200, 'message': '修改数据成功', 'data': {
                'id': userinfo.id,
                'user': userinfo.user,
                'password': userinfo.password,
                'phone': userinfo.phone,
                'create_time': userinfo.create_time,
                'headPicture': userinfo.headPicture,
                'role': list(userinfo.role.all().values()),
                'nickName': userinfo.nickName,
                'status': userinfo.status,
                'depart': {
                    'id': userinfo.depart.id,
                    'depName': userinfo.depart.depName,
                    'statu': userinfo.depart.statu,
                    'depTime': userinfo.depart.depTime,
                    'children': list(userinfo.depart.children.values())
                }
            }}
        )

    def delete(self, request, pk):
        try:
            userinfo = User.objects.get(id=pk)
        except:
            return JsonResponse({'error': '错误信息'}, status=400)
        userinfo.delete()
        return JsonResponse({'code': 200, 'message': '删除成功'})

# 角色表正向查询


class RolesModel(View):
    def get(self, request):
        try:
            roleinfo = Role.objects.all()
            print(',,,,,,,,,,,,,', roleinfo)
            rolelist = []
            for i in roleinfo:
                print('...............', i.menus)
                rolelist.append(
                    {
                        'id': i.id,
                        'role': i.role,
                        'status': i.status,
                        'menus': list(i.menus.all().values()),
                        'user': list(i.user_set.all().values()),
                        'identify': i.identify,
                        'roleTime': i.roleTime
                    }
                )
            return JsonResponse({
                'code': 200,
                'message': '获取角色信息成功',
                'data': rolelist
            })
        except:
            return JsonResponse({
                'code': 400,
                'message': '获取角色信息失败'
            })

    def post(self, request):
        data = json.loads(request.body)
        newrole = Role.objects.create(role=data['role'], status=data['status'],
                                      identify=data['identify'], roleTime=data['roleTime'])
        newrole.menus.set(data['menus'])
        for i in data['user']:  # 传递的是存放id的数组，如[1,2,3]
            newrole.user_set.add(i)
        return JsonResponse({'code': 200, 'message': '添加角色数据成功'})

# 角色表单个数据查询、修改和删除，反向的
class RoleModel(View):
    def get(self, request, pk):
        try:
            roleinfo = Role.objects.get(id=pk)
        except:
            return JsonResponse({'error': '错误信息'}, status=400)
        return JsonResponse(
            {'code': 200, 'message': '请求成功', 'data': {
                'id': roleinfo.id,
                'role': roleinfo.role,
                'status': roleinfo.status,
                'identify': roleinfo.identify,
                'roleTime': roleinfo.roleTime,
                'menus': list(roleinfo.menus.all().values()),
                'user': list(roleinfo.user_set.all().values())
            }}
        )

    def put(self, request, pk):
        data = json.loads(request.body)
        role = data.get('role')
        status = data.get('status')
        identify=data.get('identify')
        roleTime=data.get('roleTime')

        roleinfo = Role.objects.get(id=pk)
        roleinfo.role = role
        roleinfo.status = status
        roleinfo.identify=identify
        roleinfo.roleTime=roleTime
        roleinfo.menus.set(data['menus'])
        roleinfo.user_set.add(data['user'])
        roleinfo.save()
        return JsonResponse(
            {'code': 200, 'message': '修改数据成功', 'data': {
                'id': roleinfo.id,
                'role': roleinfo.role,
                'status': roleinfo.status,
                'identify': roleinfo.identify,
                'roleTime': roleinfo.roleTime,
                'menus': list(roleinfo.menus.all().values()),
                "user": list(roleinfo.user_set.all().values())
            }}
        )

    def delete(self, request, pk):
        try:
            roleinfo = Role.objects.get(id=pk)
        except:
            return JsonResponse({'error': '错误信息'}, status=400)
        roleinfo.delete()
        return JsonResponse({'code': 200, 'message': '删除成功'})

#权限菜单表多个查询
class MenusModel(View):
    def get(self, request):
        try:
            menuinfo = Menu.objects.all()
            menulist = []
            for i in menuinfo:
                print('检测数据', i.metalist)
                menulist.append(
                    {
                        "id": i.id,
                        'name': i.name,
                        'path': i.path,
                        'component': i.component,
                        'status': i.status,
                        'menuTime': i.menuTime,
                        'identify': i.identify,
                        'children': list(i.children.values()),
                        'meta': {
                            'id': i.metalist.id,
                            'title': i.metalist.title,
                            'icon': i.metalist.icon,
                            'type': i.metalist.type,
                            'affix': i.metalist.affix
                        }
                    }
                )
            return JsonResponse({
                'code': 200,
                'message': '获取菜单信息成功',
                'data': menulist
            }, safe=False)
        except:
            return JsonResponse({
                'code': 400,
                'message': '获取菜单信息失败'
            })

    def post(self, request):
        data = json.loads(request.body)
        mid = data['metalist']
        print(mid)
        metainfo = Metalist.objects.get(id=mid)
        newmenu = Menu.objects.create(name=data['name'], path=data['path'], component=data['component'],
                                      metalist=metainfo,status=data['status'],
                                      menuTime=data['menuTime'],identify=data['identify'])
        if data['children'] is not None:
            for i in data['children']:  # 传递的是存放id的数组，如[1,2,3]
                newmenu.children.add(i)
        return JsonResponse({'code': 200, 'message': '添加数据成功'})

#部门表多个查询
class DepartsModel(View):
    def get(self,request):
        try:
            depinfo=Depart.objects.all()
            deplist=[]
            for i in depinfo:
                for j in i.children:
                    print(j)
                    deplist.append(
                        {
                            'id': i.id,
                            'depName': i.depName,
                            'statu': i.statu,
                            'depTime': i.depTime,
                            # 'user':list(i.user_set.all().values()),
                            # 'children':list(i.children.values())
                            'children':list(j)
                        }
                    )
                return JsonResponse({
                    'code': 200,
                    'message': '获取部门信息成功',
                    'data': deplist
                }, safe=False)
        except:
            return JsonResponse({
                'code': 400,
                'message': '获取用户信息失败'
            })

    def post(self,request):
        pass


from rest_framework.viewsets import ModelViewSet
from .serializer import *
class DepartView(ModelViewSet):
    # queryset = Menu.objects.filter(parentId__id=None)
    queryset = Depart.objects.all()
    serializer_class = DepartSerializer